package com.boot.scripts;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class LuaScriptLoader {
    private final RedisTemplate<String, Object> redisTemplate;

    private final DefaultRedisScript<Long> stockDeductScript;

    public LuaScriptLoader(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.stockDeductScript = new DefaultRedisScript<>();
        //明确返回值类型为Long，否则会被默认转换为Status类型
        this.stockDeductScript.setResultType(Long.class);
        Resource resource = new ClassPathResource("scripts/stock_deduct.lua");
        if (!resource.exists()) {
            throw new RuntimeException("Lua脚本文件未找到:");
        }
        this.stockDeductScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("scripts/stock_deduct.lua")));
    }

    public boolean deductStock(String productKey, String orderKey, String userId, int quantity) {
            List<String> keys = Arrays.asList(productKey, orderKey);
        try {
                Long result = redisTemplate.execute(
                        stockDeductScript,
                        keys,
                        userId,
                        String.valueOf(quantity)
                );
            return result != null && result == 1L;
        } catch (RedisSystemException e) {
            log.info("Redis操作失败，根因：{}", e.getMessage());
            throw e;
        }
    }

    public void startServer() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formatTime = formatter.format(now);
        redisTemplate.opsForValue().set("LuaScriptLoader:start:time", formatTime);
    }
}
